﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ConfApp.Infrastructure;
using ConfApp.Models;
using Microsoft.Phone.Reactive;

namespace ConfApp.Services.Podcasts
{
    public class PodcastUpdateService : IPodcastUpdateService
    {
        public const string UpdatingTask = "UpdatingTask";

        private IPodcastServiceClient _podcastServiceClient;
        private IPodcastStore _podcastStore;

        public PodcastUpdateService(
            IPodcastServiceClient twitterServiceClient,
            IPodcastStore twitterStore)
        {
            _podcastServiceClient = twitterServiceClient;
            _podcastStore = twitterStore;
        }

        public IObservable<TaskCompletedSummary> StartUpdating()
        {
            return _podcastServiceClient.GetPodcasts()
                .Select(podcastBatch =>
                            {
                                var count = _podcastStore.SavePodcasts(podcastBatch.Podcasts);

                                return new TaskCompletedSummary
                                {
                                    Task = UpdatingTask,
                                    Result = TaskSummaryResult.Success,
                                    Context = count.ToString()
                                };
                            })
                            .Catch(
                        (Exception exception) =>
                        {
                            if (exception is WebException)
                            {
                                var webException = exception as WebException;
                                var summary = ExceptionHandling.GetSummaryFromWebException(UpdatingTask, webException);
                                return Observable.Return(summary);
                            }

                            if (exception is UnauthorizedAccessException)
                            {
                                return Observable.Return(new TaskCompletedSummary { Task = UpdatingTask, Result = TaskSummaryResult.AccessDenied });
                            }

                           ;
                            return Observable.Return(
                                new TaskCompletedSummary { Task = UpdatingTask, Result = TaskSummaryResult.UnknownError }
                                );
                        });
        }
    }
}
